<template>
  <div id="userLogin">
    <h2 style="margin-bottom: 20px;">用户登录</h2>
    <a-form ref="formRef" :model="form" :style="{ width: '100%' }"  :rules="rules" @submit="handleSubmit">
      <!-- 账号 -->
      <a-form-item tooltip="账号不能小于4位" required field="userAccount"  label="账号:" :validate-trigger="['input','blur']">
        <a-input
          v-model="form.userAccount"
          placeholder="请输入账号..."
        />
      </a-form-item>

      <!-- 密码 -->
      <a-form-item tooltip="密码不能小于8位" required field="userPassword"  label="密码:" :validate-trigger="['input','blur']">
        <a-input-password v-model="form.userPassword" placeholder="请输入密码..." />
      </a-form-item>

      <!-- 登录 -->
      <a-form-item>
        <div style="width: 100%;display: flex;align-items: center;justify-content: space-between;">
          <a-button  type="primary" style="width:50%" html-type="submit">登录</a-button>
          <router-link style="text-decoration: none;" to="/user/register">->去注册</router-link>
        </div>
      </a-form-item>
      
    </a-form>
  </div>
  
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import API from '@/api'
import { userLoginUsingPost } from '@/api/userController';
import { useLoginUserStore } from '@/store/userStore';
import message from '@arco-design/web-vue/es/message'
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute()
const loginUserStore = useLoginUserStore();
const formRef = ref();

// 定义表单数据
const form = reactive({
  userAccount: '',
  userPassword: ''
} as API.UserLoginRequest);

//校验规则
const rules = {
  userAccount: [
    { required: true, message: '账号不能为空' },
    {minLength:4, message: '账号长度不能小于4位' }
  ],
  userPassword: [
    { required: true, message: '密码不能为空' },
    {minLength:8, message: '密码长度不能小于8位'}
  ],
}

// 提交表单
const handleSubmit = async ({values, errors}: any) => {
  // console.log(values, errors)
  if(!errors) {
    const res = await userLoginUsingPost(form)
  if(res.data.code === 0) {
    // 获取用户信息
    await loginUserStore.fetchLoginUser()
    message.success('登录成功')
    if(route.query.redirect) {
      router.replace({ path: route.query.redirect as string })
    } else {
      router.replace({ path: '/' })
    }
  } else {
    message.error('登录失败:' + res.data.message as string)
  }
  } 
}

</script>
<style lang="scss" scoped>
#userLogin {
  width: 40vw;
  padding: 20px;
  border-radius: 10px;
  background: rgba(255,255,255,.6);
  margin: 0 auto;
  min-width: 400px;
  // position: fixed;
  // top: 50%;
  // left: 50%;
  // transform: translate(-50%, -50%);
}
</style>